package drds.binlog.database_driver.packets.server;

import drds.binlog.common.Authors;
import drds.binlog.database_driver.packets.PacketWithHeaderPacket;
import drds.binlog.database_driver.utils.Bytes;
import drds.common.Author;
import lombok.Getter;
import lombok.Setter;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

@Author(name = Authors.LI_YANG)
public class EofPacket extends PacketWithHeaderPacket
{
    @Setter
    @Getter
    public byte fieldCount;
    @Setter
    @Getter
    public int warningCount;
    @Setter
    @Getter
    public int statusFlag;

    /**
     * <pre>
     *  VERSION 4.1
     *  Bytes                 Name
     *  -----                 ----
     *  1                     field_count, always = 0xfe
     *  2                     warning_count
     *  2                     Status Flags
     * </pre>
     */
    public void fromBytes(byte[] bytes)
    {
        int index = 0;
        // 1. read field count
        fieldCount = bytes[index];
        index++;

        // 2. read warning count
        this.warningCount = Bytes.readUnsigned2IntLittleEndian(bytes, index);
        index += 2;

        // 3. read status flag
        this.statusFlag = Bytes.readUnsigned2IntLittleEndian(bytes, index);
        // log_position_manager += 2;

        // end read
    }

    public byte[] toBytes() throws IOException
    {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(5);
        byteArrayOutputStream.write(this.fieldCount);
        Bytes.writeUnsigned2IntLittleEndian(byteArrayOutputStream, this.warningCount);
        Bytes.writeUnsigned2IntLittleEndian(byteArrayOutputStream, this.statusFlag);
        return byteArrayOutputStream.toByteArray();
    }

}
